package cn.innosmart.aq.view.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.tutk.p2p.ConnectionEntity;
import com.tutk.p2p.ConnectionManager;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.innosmart.aq.R;
import cn.innosmart.aq.bean.AquariumBean;
import cn.innosmart.aq.bean.CommandBean;
import cn.innosmart.aq.bean.RuleBean;
import cn.innosmart.aq.bean.TriggerBean;
import cn.innosmart.aq.customize.CancelScrollViewPager;
import cn.innosmart.aq.customize.CustomNavigationBar;
import cn.innosmart.aq.manager.RuleManager;
import cn.innosmart.aq.view.activity.base.BaseActivity;
import cn.innosmart.aq.view.fragment.RuleStep1Fragment;
import cn.innosmart.aq.view.fragment.RuleStep2Fragment;
import cn.innosmart.aq.view.fragment.RuleStep3Fragment;

/**
 * Created by David on 2015/8/14.
 */
public class RuleActivity extends BaseActivity {
    public static RuleBean ruleBean;
    private final int EXIT = 0;
    private final int ADDRULE = 1;
    private final int MODIFYRULE = 2;
    public AquariumBean aquariumBean;
    private LinearLayout main;
    private LinearLayout llContent;
    private CustomNavigationBar bar;
    private CancelScrollViewPager vpRuleStep;
    private RelativeLayout ruleBottom;
    ;
    private Button btRuleLeft;
    private Button btRuleRight;
    private List<Fragment> mFragments = new ArrayList<Fragment>();
    private String rule_id;
    private FragmentPagerAdapter viewpagerAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
        @Override
        public int getCount() {
            return mFragments.size();
        }

        @Override
        public Fragment getItem(int arg0) {
            return mFragments.get(arg0);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            return super.instantiateItem(container, position);
        }

        @Override
        public Parcelable saveState() {
            return super.saveState();
        }

        @Override
        public void setPrimaryItem(ViewGroup container, int position, Object object) {
            super.setPrimaryItem(container, position, object);
        }
    };
    /**
     * ViewPager的当前选中页
     */
    private int currentIndex;
    /**
     * 设置界面Toolbar
     */
    private Toolbar toolbar;
    private ConnectionEntity connectionEntity;
    private int position = -1;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            connectionEntity = ConnectionManager.getInstance().getCurrentConnectionEntity();
            switch (msg.what) {
                case EXIT:
                    //退出
                    exit();
                    break;
                case ADDRULE:
                    //添加规则
                    if (TextUtils.isEmpty(ruleBean.getTitle())) {
                        showToast(getString(R.string.name_can_not_empty));
                        break;
                    }
                    if (checkRepeatTitle(ruleBean.getTitle())) {
                        showToast(getString(R.string.name_had_used));
                        break;
                    }
                    if (!checkEveryDayTime()) {
                        break;
                    }
                    //计算WEEks
                    caculateWeekdays();
                    loadingDialog();
                    //发送规则添加指令
                    RuleManager.getInstance().Add(connectionEntity, ruleBean.toParams().toString(), new RuleManager.AddCallBack() {
                        @Override
                        public void onAddResponseCallBack(int ret, String ruleid) {
                            if (ret == 0) {
                                ruleBean.setId(ruleid);
                                aquariumBean.getRuleList().add(ruleBean);
                                hideloadingDialog();
                                exit();
                            }
                        }
                    });
                    break;
                case MODIFYRULE:
                    //修改规则
                    if (TextUtils.isEmpty(ruleBean.getTitle())) {
                        showToast(getString(R.string.name_can_not_empty));
                        break;
                    }
                    if (checkRepeatTitle(ruleBean.getTitle())) {
                        showToast(getString(R.string.name_had_used));
                        return;
                    }
                    if (!checkEveryDayTime()) {
                        break;
                    }
                    caculateWeekdays();
                    loadingDialog();
                    //发送规则更新的指令
                    RuleManager.getInstance().Update(connectionEntity, ruleBean.toParams().toString(), new RuleManager.UpdateCallBack() {
                        @Override
                        public void onUpdateResponseCallBack(int ret, String ruleid) {
                            if (ret == 0) {
                                for (int i = 0; i < aquariumBean.getRuleList().size(); i++) {
                                    RuleBean oldruleBean = (RuleBean) aquariumBean.getRuleList().get(i);
                                    if (rule_id.equals(oldruleBean.getId())) {
                                        aquariumBean.getRuleList().remove(i);
                                        aquariumBean.getRuleList().add(ruleBean);
                                        hideloadingDialog();
                                        exit();
                                    }
                                }
                            } else {
                                hideloadingDialog();
                                exit();
                            }
                        }
                    });
                    break;
            }
        }
    };
    private View.OnClickListener mBtnOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.bt_rule_left:
                    //往后一步
                    if (currentIndex == 2) {
                        btRuleRight.setText(getString(R.string.activity_auto_next));
                    }
                    if (currentIndex != 0)
                        currentIndex = currentIndex - 1;
                    vpRuleStep.setCurrentItem(currentIndex);
                    if (currentIndex == 0) {
                        btRuleLeft.setVisibility(View.GONE);
                    }
                    break;
                case R.id.bt_rule_right:
                    //往前一步
                    if (currentIndex == 0) {
                        if (ruleBean.getTriggers() == null || ruleBean.getTriggers().size() == 0) {
                            showToast(getString(R.string.ruleactivity_add_triggers_first));
                            break;
                        }
                    } else if (currentIndex == 1) {
                        if (ruleBean.getCommands() == null || ruleBean.getCommands().size() == 0) {
                            showToast(getString(R.string.ruleactivity_add_commands_first));
                            break;
                        }
                    }
                    if (currentIndex == 0) {
                        btRuleLeft.setVisibility(View.VISIBLE);
                    }
                    if (currentIndex == 2) {
                        if (rule_id == null)
                            mHandler.sendEmptyMessage(ADDRULE);
                        else
                            mHandler.sendEmptyMessage(MODIFYRULE);
                    } else {
                        if (currentIndex != 2) {
                            currentIndex = currentIndex + 1;
                        }
                        vpRuleStep.setCurrentItem(currentIndex);
                        if (currentIndex == 2) {
                            btRuleRight.setText(getString(R.string.save));
                        }
                    }
                    break;
            }
        }
    };

    /**
     * 初始化Fragment
     */
    private void initialFragments() {
        RuleStep1Fragment ruleStep1 = new RuleStep1Fragment();
        RuleStep2Fragment ruleStep2 = new RuleStep2Fragment();
        RuleStep3Fragment ruleStep3 = new RuleStep3Fragment();
        mFragments.add(ruleStep1);
        mFragments.add(ruleStep2);
        mFragments.add(ruleStep3);
    }

    /**
     * 初始化控件
     */
    private void assignViews() {
        main = (LinearLayout) findViewById(R.id.main);
        llContent = (LinearLayout) findViewById(R.id.ll_content);
        bar = (CustomNavigationBar) findViewById(R.id.bar);
        vpRuleStep = (CancelScrollViewPager) findViewById(R.id.vp_rule_step);
        ruleBottom = (RelativeLayout) findViewById(R.id.rule_bottom);
        btRuleLeft = (Button) findViewById(R.id.bt_rule_left);
        btRuleRight = (Button) findViewById(R.id.bt_rule_right);
        btRuleRight.setOnClickListener(mBtnOnClickListener);
        btRuleLeft.setOnClickListener(mBtnOnClickListener);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rule);
        String aquariumId = getIntent().getStringExtra("aquarium");
        aquariumBean = AquariumBean.findAquariumById(aquariumId);
        rule_id = getIntent().getStringExtra("rule"); //For Edit
        setBar();
        initPosition();
        assignViews();
//        重设数据
        resetData(rule_id);
        initialFragments();
        initListener();
        vpRuleStep.setAdapter(viewpagerAdapter);
    }

    /**
     * 如果修改，copy一份数据
     *
     * @param rule_id
     */
    private void resetData(String rule_id) {
        ruleBean = new RuleBean();
        ruleBean.setPlace(aquariumBean.getId());
        ruleBean.pns_priority = 1;
        if (rule_id != null) {
            for (int i = 0; i < aquariumBean.getRuleList().size(); i++) {
                RuleBean ruleBeans = (RuleBean) aquariumBean.getRuleList().get(i);
                ArrayList<CommandBean> commandBeans = new ArrayList<CommandBean>();
                HashMap<String, TriggerBean> actiongs = new HashMap<String, TriggerBean>();
                HashMap<Integer, JSONArray> timeline = new HashMap<>();
                if (ruleBeans.getId().equals(rule_id)) {
                    ruleBean.setEnabled(ruleBeans.getEnabled());
                    ruleBean.setPns(ruleBeans.getPns());
                    ruleBean.setRepeat_type(ruleBeans.getRepeat_type());
                    ruleBean.pns_priority = ruleBeans.pns_priority;
                    commandBeans.addAll(ruleBeans.getCommands());
                    ruleBean.setCommands(commandBeans);
                    ruleBean.setEnd(ruleBeans.getEnd() == null ? null : new String(ruleBeans.getEnd()));
                    ruleBean.setStart(ruleBeans.getStart() == null ? null : new String(ruleBeans.getStart()));
                    ruleBean.setIcon_data(ruleBeans.getIcon_data() == null ? null : new String(ruleBeans.getIcon_data()));
                    ruleBean.setId(ruleBeans.getId() == null ? null : new String(ruleBeans.getId()));
                    ruleBean.setPlace(ruleBeans.getPlace() == null ? null : new String(ruleBeans.getPlace()));
                    timeline.putAll(ruleBeans.getTimeLine());
                    ruleBean.setTimeLine(timeline);
                    ruleBean.setWeekdays(ruleBeans.getWeekdays());
                    actiongs.putAll(ruleBeans.getTriggers());
                    ruleBean.setTriggers(actiongs);
                    ruleBean.setTitle(ruleBeans.getTitle() == null ? null : new String(ruleBeans.getTitle()));
                    break;
                }
            }
        }
    }

    /**
     * 初始化监听器
     */
    private void initListener() {
        /**
         * 设置监听
         */
        vpRuleStep.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                // 重置所有TextView的字体颜色
                switch (position) {
                    case 0:
                        btRuleLeft.setVisibility(View.GONE);
                        btRuleRight.setText(getString(R.string.activity_auto_next));
                        break;
                    case 1:
                        btRuleLeft.setVisibility(View.VISIBLE);
                        btRuleRight.setText(getString(R.string.activity_auto_next));
                        break;
                    case 2:
                        btRuleLeft.setVisibility(View.VISIBLE);
                        btRuleRight.setText(getString(R.string.save));
                        break;
                }
                currentIndex = position;
            }

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                /**
                 * 利用position和currentIndex判断用户的操作是哪一页往哪一页滑动
                 * 然后改变根据positionOffset动态改变TabLine的leftMargin
                 */
                if (currentIndex == 0 && position == 0)// 0->1
                {
                } else if (currentIndex == 1 && position == 0) // 1->0
                {
                } else if (currentIndex == 1 && position == 1) // 1->2
                {
                } else if (currentIndex == 2 && position == 1) // 2->1
                {
                }
                if (positionOffset > 0) {
                    bar.changing(position, currentIndex, positionOffset);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void setBar() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        ((ImageView) findViewById(R.id.iv_headicon)).setImageResource(R.drawable.toolbar_back);
        toolbar.setTitle("");
        if (rule_id == null)
            ((TextView) findViewById(R.id.tv_toolbar)).setText(getString(R.string.activity_add_rule));
        else
            ((TextView) findViewById(R.id.tv_toolbar)).setText(getString(R.string.activity_modify_rule));
        setSupportActionBar(toolbar);
        findViewById(R.id.iv_headicon).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                mDrawer.openDrawer(GravityCompat.START);
                mHandler.sendEmptyMessage(EXIT);
            }
        });
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    /**
     * 检查时间
     *
     * @return
     */
    private boolean checkEveryDayTime() {
        String startTime = ruleBean.getStart();
        String[] timeStartArray = startTime.split(":");
        int startHour = Integer.valueOf(timeStartArray[0]);
        int startMinute = Integer.valueOf(timeStartArray[1]);
        String endTime = ruleBean.getEnd();
        String[] timeEndArray = endTime.split(":");
        int endHour = Integer.valueOf(timeEndArray[0]);
        int endMinute = Integer.valueOf(timeEndArray[1]);
        if (startHour > endHour) {
            Toast.makeText(this, R.string.activity_rule_end_above_start, Toast.LENGTH_SHORT).show();
            return false;
        } else if (startHour == endHour) {
            if (startMinute < endMinute) {
                return true;
            } else {
                Toast.makeText(this, R.string.activity_rule_end_above_start, Toast.LENGTH_SHORT).show();
                return false;
            }
        } else {
            return true;
        }
    }

    /**
     * 计算week
     */
    private void caculateWeekdays() {
        if (ruleBean != null) {
            int weekdays = 0;
            if (ruleBean.getTimeLine().get(1) != null) {
                weekdays += 1 << 0;
            }
            if (ruleBean.getTimeLine().get(2) != null) {
                weekdays += 1 << 1;
            }
            if (ruleBean.getTimeLine().get(3) != null) {
                weekdays += 1 << 2;
            }
            if (ruleBean.getTimeLine().get(4) != null) {
                weekdays += 1 << 3;
            }
            if (ruleBean.getTimeLine().get(5) != null) {
                weekdays += 1 << 4;
            }
            if (ruleBean.getTimeLine().get(6) != null) {
                weekdays += 1 << 5;
            }
            if (ruleBean.getTimeLine().get(0) != null) {
                weekdays += 1 << 6;
            }
            ruleBean.setWeekdays(weekdays);
        }
    }

    @Override
    protected void onResume() {
        setBaseDialogContext(this);
        super.onResume();
        toolbar.setNavigationIcon(null);
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    public void onBackPressed() {
        ruleBean = null;
        exit();
    }

    /**
     * 初始化Position
     */
    private void initPosition() {
        if (rule_id != null && aquariumBean.getRuleList() != null) {
            for (int i = 0; i < aquariumBean.getRuleList().size(); i++) {
                RuleBean ruleBean = (RuleBean) aquariumBean.getRuleList().get(i);
                if (ruleBean.getId().equals(rule_id)) {
                    position = i;
                }
            }
        }
    }

    /**
     * 检查重复的标题
     *
     * @param title
     * @return
     */
    private boolean checkRepeatTitle(String title) {
        if (ruleBean.getId() == null && aquariumBean.getRuleList() != null) {
            for (Object object : aquariumBean.getRuleList()) {
                if (title.equals(((RuleBean) object).getTitle())) {
                    return true;
                }
            }
        } else if (ruleBean.getId() != null && aquariumBean.getRuleList() != null) {
            for (int i = 0; i < aquariumBean.getRuleList().size(); i++) {
                if (title.equals(((RuleBean) aquariumBean.getRuleList().get(i)).getTitle())) {
                    if (i == position) {
                        continue;
                    } else {
                        return true;
                    }
                }
            }
        }
        return false;
    }

}
